package com.atguigu.guli.service.oss.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.atguigu.guli.service.oss.service.FileService;
import com.atguigu.guli.service.oss.util.OssProperties;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.InputStream;
import java.util.UUID;

/**
 * @author helen
 * @since 2020/6/23
 */
@Service
public class FileServiceImpl implements FileService {

    @Autowired
    private OssProperties ossProperties;


    @Override
    public String upload(InputStream inputStream, String module, String oFilename) {

        String endpoint = ossProperties.getEndpoint();
        String keyId = ossProperties.getKeyId();
        String keySecret = ossProperties.getKeySecret();
        String bucketName = ossProperties.getBucketName();

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, keyId, keySecret);

        //文件路径：avatar/2020/06/23/文件名.扩展名
        String folder = new DateTime().toString("yyyy/MM/dd");//日期目录
        String extentionName = oFilename.substring(oFilename.lastIndexOf("."));//扩展名
        String fileName = UUID.randomUUID().toString();//文件名
        String key =  module + "/" + folder + "/" + fileName + extentionName;

        //文件上传
        ossClient.putObject(bucketName, key, inputStream);

        // 关闭OSSClient。
        ossClient.shutdown();

        //返回url地址：
        // https://guli-file-200211.oss-cn-beijing.aliyuncs.com/avatar/default.jpg
        return "https://" + bucketName + "." +  endpoint + "/" + key;
    }

    @Override
    public void removeFile(String url) {

        String endpoint = ossProperties.getEndpoint();
        String keyId = ossProperties.getKeyId();
        String keySecret = ossProperties.getKeySecret();
        String bucketName = ossProperties.getBucketName();

        String host = "https://" + bucketName + "." +  endpoint + "/";
        String objectName = url.substring(host.length());

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, keyId, keySecret);

        // 删除文件。如需删除文件夹，请将ObjectName设置为对应的文件夹名称。如果文件夹非空，则需要将文件夹下的所有object删除后才能删除该文件夹。
        ossClient.deleteObject(bucketName, objectName);

        // 关闭OSSClient。
        ossClient.shutdown();
    }
}
